package com.closer.service.api;

import com.closer.service.biz.chatHistory.dto.ChatHistoryQueryRequest;
import com.closer.service.biz.user.dto.vo.LoginUserVO;
import com.closer.service.support.annotation.AuthCheck;
import com.closer.service.support.common.BaseResponse;
import com.closer.service.support.common.ResultUtils;
import com.closer.service.support.constant.UserConstant;
import com.closer.service.support.exception.ErrorCode;
import com.closer.service.support.exception.ThrowUtils;
import com.mybatisflex.core.paginate.Page;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import com.closer.service.biz.chatHistory.entity.ChatHistory;
import com.closer.service.biz.chatHistory.service.ChatHistoryService;

import java.time.LocalDateTime;

import static com.closer.service.support.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 对话历史 控制层。
 *
 * @author closer
 */
@RestController
@RequestMapping("/chatHistory")
public class ChatHistoryController {

    private final ChatHistoryService chatHistoryService;

    public ChatHistoryController(ChatHistoryService chatHistoryService) {
        this.chatHistoryService = chatHistoryService;
    }


    @GetMapping("/app/{appId}")
    public BaseResponse<Page<ChatHistory>> listAppChatHistory(@PathVariable Long appId,
                                                              @RequestParam(defaultValue = "10") int pageSize,
                                                              @RequestParam(required = false) LocalDateTime lastCreateTime,
                                                              HttpServletRequest request) {
        var userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        var loginUser = (LoginUserVO) userObj;
        var result = chatHistoryService.listAppChatHistoryByPage(appId, pageSize, lastCreateTime, loginUser);
        return ResultUtils.success(result);
    }

    /**
     * 管理员分页查询所有对话历史
     *
     * @param chatHistoryQueryRequest 查询请求
     * @return 对话历史分页
     */
    @PostMapping("/admin/list/page/vo")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<ChatHistory>> listAllChatHistoryByPageForAdmin(@RequestBody ChatHistoryQueryRequest chatHistoryQueryRequest) {
        ThrowUtils.throwIf(chatHistoryQueryRequest == null, ErrorCode.PARAMS_ERROR);
        var pageNum = chatHistoryQueryRequest.getPageNum();
        var pageSize = chatHistoryQueryRequest.getPageSize();
        // 查询数据
        var queryWrapper = chatHistoryService.getQueryWrapper(chatHistoryQueryRequest);
        var result = chatHistoryService.page(Page.of(pageNum, pageSize), queryWrapper);
        return ResultUtils.success(result);
    }


}
